package com.okami.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.PortResolver;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: TanJingyu
 * @create: 2020-07-01 17:08
 **/
@RestController
public class HelloController {
    private PortResolver portResolver = new PortResolverImpl();

    @GetMapping("/hello")
    @PreAuthorize("hasRole('adminnnn')")
    public String hello(HttpServletRequest request){
        return "hello";
    }

    @GetMapping("/currUser")
    public String currUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getName();
    }

    @GetMapping("/currUser/authority")
    public Object currUserAuthority(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities();
    }

    @GetMapping("/currUser/user")
    public String currUser(Authentication authentication){
        return authentication.getName();
    }

    @GetMapping("/url")
    public void url(HttpServletRequest request){
        String uri = "/login";

        System.out.println("----------");

        SecurityContextHolder.getContext().getAuthentication();

        //UrlUtils用来验证是否是一个完整的请求地址
        if (UrlUtils.isAbsoluteUrl(uri)) {
            System.out.println("是一个完整地址请求！");
        }

        System.out.println("scheme: " + request.getScheme());
        System.out.println("serverName: " + request.getServerName());
        System.out.println("port: " + portResolver.getServerPort(request));
        System.out.println("pathInfo: " + request.getPathInfo());

        System.out.println(request.getRemoteAddr());
    }

    @GetMapping("/queryAll")
    @PreAuthorize("hasAuthority('queryAll')")
    public String queryAll(){
        return "queryAll";
    }

}
